// pages/category/index.js
import { request } from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
    data: {
        //左侧菜单数据
        leftMenuList: [],
        //右侧菜单数据
        rightContent: [],
        //被点击左侧菜单
        currentIndex: 0,
        //右侧内容的滚动条距离顶部的距离
        scrollTop: 0

    },
    //接口返回数据
    Cates: [],

    onLoad: function(options) {
        //获取本地存储的数据
        const Cates = wx.getStorageSync("cates");
        //判断
        if (!Cates) {
            //不存在
            this.getCates();
        } else {
            //有数据了 需要定义过期时间
            if (Date.now() - Cates.time > 1000 * 10) {
                this.getCates();
            } else {
                this.Cates = Cates.data;
                let leftMenuList = this.Cates.map(v => v.cat_name);
                //构造右侧商品数据
                let rightContent = this.Cates[0].children;
                this.setData({
                    leftMenuList,
                    rightContent
                })
            }

        }
    },
    //获取分类数据
    async getCates() {
        // request({
        //         url: "/categories"
        //     })
        //     .then(res => {
        //         this.Cates = res.data.message;
        //         //把接口数据存入本地存储
        //         wx.setStorageSync("cates", { time: Date.now(), data: this.Cates });
        //         //构造左侧菜单数据
        //         let leftMenuList = this.Cates.map(v => v.cat_name);
        //         //构造右侧商品数据
        //         let rightContent = this.Cates[0].children;
        //         this.setData({
        //             leftMenuList,
        //             rightContent
        //         })
        //     })
        //使用asyncg await
        const res = await request({ url: "/categories" });
        this.Cates = res;
        //把接口数据存入本地存储
        wx.setStorageSync("cates", { time: Date.now(), data: this.Cates });

        //构造左侧菜单数据
        let leftMenuList = this.Cates.map(v => v.cat_name);
        //构造右侧商品数据
        let rightContent = this.Cates[0].children;
        this.setData({
            leftMenuList,
            rightContent
        })


    },
    //左侧点击事件
    handleItemTap(e) {
        const { index } = e.currentTarget.dataset;
        let rightContent = this.Cates[index].children;

        this.setData({
            currentIndex: index,
            rightContent,
            //重新设置距离 
            scrollTop: 0
        })

    }

})